const { createServer } = require("http");
const { resolve } = require("path");
const { existsSync, createReadStream } = require("fs");

server = createServer(function fn(req, res) {
  const fileName = resolve(__dirname, `.${req.url}`);

  res.setHeader("Access-Control-Allow-Origin", "*");
  // 允许的header类型
  res.setHeader("Access-Control-Allow-Headers", "content-type");
  // 跨域允许的请求方式
  res.setHeader("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");

  // 判断本地文件是否存在
  if (existsSync(fileName)) {
    const stream = createReadStream(fileName);
    stream.pipe(res);
  } else {
    res.writeHead(404, { "Content-Type": "text/plain" });
    res.write("THE RESOURCE NOT FOUND", "utf-8");
  }
});

server.listen(8000);
